// pages/contribution/contribution.js
const customRequst = require('../../common/customRequst');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    newsList: [],
    id: '0'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    let that = this;
    if (option.orderid) {
      that.setData({
        id: option.orderid
      })
    }
  },
  onShow: function () {
    let that = this
    if (that.data.id) {
      customRequst.postRequest('api/contribution/handlelist', {
        id: that.data.id
      }).then(res => {
        if (res.code == 1) {

          let newsList = res.data;
          for(let i in newsList){
            newsList[i]['content'] = that.searchDown(newsList[i]['content']);
          }
          that.setData({
            newsList: newsList
          })
        } else {
          wx.showToast({
            title: res.msg,
          })
        }
      })
    }
  },

  //下载文件
  downFile:function(e){
    let url = e.currentTarget.dataset.url;
    wx.downloadFile({
      url: url,
      success:function(re){
        const tempFilePath = re.tempFilePath;
        console.log(tempFilePath)
        // 保存文件
        wx.saveFile({
          tempFilePath,
          success: function (res) {
            const savedFilePath = res.savedFilePath;
            console.log(savedFilePath)
            // 打开文件
            wx.openDocument({
              filePath: savedFilePath,
              success: function (res) {
                console.log('打开文档成功'+ res)
              },
            });
          },
          fail: function (err) {
            console.log('保存失败：', err)
          }
        });
      }
    });
  },

  //获取需要下载的文件
  searchDown:function(str){
      let retunData={
        txt:'',
        a:{}
      }
      if(str.indexOf('<a') >= 0){
        let reg = /<p\b[^<>]*>.*?<\/p>/i;
        let a = str.match(reg);
        retunData.txt = str.replace(reg,'');
        if(a){
          reg = /<span>(.*?)<\/span>/i;
          let txt = a[0].match(reg);
          if(txt){
            txt = txt[1];
          }
          reg = /href=[\'\"]?([^\'\"]*)[\'\"]?/i;
          let href = a[0].match(reg);
          if(href){
            href = href[1];
          }
          retunData.a = {
            txt:txt,
            href:href,
          };
        }
      }else{
        retunData.txt = str;
      }
    return retunData;    
  }
})